<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ApplicationForm\TableDetail;
use App\Models\ApplicationForm;
use App\Models\ClassAndGradeTime;
use App\Models\Club;
use App\Models\School;
use App\Models\SchoolClassAndGrade;
use App\Models\StudentApplication;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use function foo\func;

class ApplicationFormController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'ApplicationForm';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ApplicationForm());

        $grid->column('id', __('Id'));
        $grid->column('form_name', __('表单名称'));
        $grid->column('school_ids', __('学校名称'))->display(function ($schoolIds) {
            $schools = School::query()->whereIn('id', $schoolIds)->get();
            $html = '<div>';
            foreach ($schools as $v) {
                $html .= "<span>{$v->school_name}</span><br/>";
            }
            $html .= '</div>';
            return $html;
        });
        $grid->column('club_ids', __('社团名称'))->display(function ($clubIds) {
            $clubs = Club::query()->whereIn('id', $clubIds)->get();
            $html = '<div>';
            foreach ($clubs as $v) {
                $html .= "<span>{$v->club_name}</span><br/>";
            }
            $html .= '</div>';
            return $html;
        });
        $grid->column('created_at', __('创建时间'));
        $grid->column('updated_at', __('更新时间'));
        // 去掉查看
        $grid->actions(function ($actions) {
            $actions->disableView();
            $actions->add(new TableDetail);
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ApplicationForm::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('form_name', __('表单名称'));
        $show->field('school_ids', __('学校名称'));
        $show->field('club_ids', __('社团名称'));
        $show->field('created_at', __('创建时间'));
        $show->field('updated_at', __('更新时间'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ApplicationForm());

        $school = School::all()->pluck('school_name', 'id');
        $school->put('-1', '全部');

        $club = Club::all()->pluck('club_name', 'id');
        $club->put('-1', '全部');

        $form->text('form_name',__('表单名称'));
        $form->multipleSelect('school_ids', __('学校'))->options($school);
        $form->multipleSelect('club_ids', __('社团'))->options($club);

        $form->saving(function (Form $form) {
            $schoolIds = array_filter($form->school_ids);
            if (in_array('-1', $schoolIds)) {
                $schoolIds = School::query()->get()->pluck('id')->toArray();
            }
            $clubIds = array_filter($form->club_ids);
            if (in_array('-1', $clubIds)) {
                $clubIds = Club::query()->get()->pluck('id')->toArray();
            }
            $form->school_ids = $schoolIds;
            $form->club_ids = $clubIds;
        });

        return $form;
    }

    public function application_form_table_detail($id, Content $content)
    {
        $formId = $id;

        //学校-社团维度
        $tab = new Tab();

        $formInfo = ApplicationForm::query()->findOrFail($formId);

        $schoolInfo = School::query()->whereIn('id',$formInfo->school_ids)->get();

        $clubInfo = Club::query()->whereIn('id',$formInfo->club_ids)->get();

        $rows = [];

        foreach ($clubInfo as $v){
            foreach ($schoolInfo as $vv){
                $temp = [$vv->school_name,$v->club_name];
                // 总人数
                $t = SchoolClassAndGrade::query()
                    ->where('school_id',$vv->id)
                    ->where('club_id',$v->id)
                    ->where('status',1)
                    ->pluck('id')->toArray();
                $totalCount = ClassAndGradeTime::query()->whereIn('class_and_grade_id',$t)->sum('max_num');
                $temp[] = $totalCount;
                $studentCount = StudentApplication::query()
                    ->where('school_id',$vv->id)
                    ->where('club_id',$v->id)
                    ->where('form_id',$formId)
                    ->count();
                $temp[] = $studentCount;
                $rows[] = $temp;
            }
        }

        // 表格组件

        $headers = ['学校', '社团班级','总人数','报名人数'];

        $table = new Table($headers, $rows);



        $grid = new Grid(new StudentApplication());
        $grid->resource('/admin/student-applications?form_id='.$formId);
        $grid->filter(function($filter)use($clubInfo,$schoolInfo){

            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            // 在这里添加字段过滤器
            $filter->like('name', '学生姓名');
            $filter->like('phone', '电话');
            $clubData = collect($clubInfo)->mapWithKeys(function ($item){
                return [$item['id']=>$item['club_name']];
            })->toArray();
            $schoolData = collect($schoolInfo)->mapWithKeys(function ($item){
                return [$item['id']=>$item['school_name']];
            })->toArray();
            $filter->in('club_id','社团班级')->multipleSelect($clubData);
            $filter->in('school_id','学校')->multipleSelect($schoolData);
        });
        $grid->model()->where('form_id',$formId);
        $grid->column('id', __('Id'));
        $grid->column('club.club_name', __('社团班级'));
        $grid->column('school.school_name', __('学校'));
        $grid->column('class_and_grade', __('年级'))->display(function ($classAndGrade){
            return "<span>{$classAndGrade['grade']} {$classAndGrade['class_name']}</span>";
        });
        $grid->column('school_class_name', __('班级'));
        $grid->column('class_and_grade_time', __('上课时间'))->display(function ($classAndGradeTime){
            return "<span>{$classAndGradeTime['week_text']}:{$classAndGradeTime['start_time']}-{$classAndGradeTime['end_time']}</span>";
        });
        $grid->column('name', __('学生姓名'));
        $grid->column('phone', __('电话'));
        $grid->column('created_at', __('报名时间'));
        $grid->actions(function ($actions) {
        });

        $tab->add('学生', $grid->render());
        $tab->add('学校-社团', $table->render());

        return $content
            ->title('详情')
            ->row($tab->render()); //显示;
    }
}
